package com.yzf.wisecoder.wisecoderservice.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yzf.uidgeneratorcore.impl.CachedUidGenerator;
import com.yzf.wisecoder.wisecodercommon.exception.RRException;
import com.yzf.wisecoder.wisecodercommon.utils.SecurityUtils;
import com.yzf.wisecoder.wisecoderservice.service.TemStoreService;
import com.yzf.wisecoder.wisecoderstorage.mysql.dao.TemStoreDao;
import com.yzf.wisecoder.wisecoderstorage.mysql.entity.TemStoreEntity;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;


/**
 * @author jianghuiyong
 * @email jianghuiyong@yunzhangfang.com
 * @date 2020-05-12 10:20:48
 */
@Service("temStoreService")
@AllArgsConstructor
public class TemStoreServiceImpl extends ServiceImpl<TemStoreDao, TemStoreEntity> implements TemStoreService {

    private final CachedUidGenerator cachedUidGenerator;

    @Override
    public List<TemStoreEntity> queryList(Map<String, Object> params) {
        String temName = (String) params.get("temName");
        List<TemStoreEntity> list = list(new QueryWrapper<TemStoreEntity>()
                .eq("deleted", Boolean.FALSE)
                .like(StrUtil.isNotBlank(temName), "tem_name", temName));
        return list;
    }

    @Override
    public boolean saveOrUpdateTemStore(TemStoreEntity temStoreEntity) {
        TemStoreEntity temStoreEntity1 = getOne(new QueryWrapper<TemStoreEntity>()
                .eq("tem_name", temStoreEntity.getTemName()));
        if (temStoreEntity1 != null && (temStoreEntity.getTemId() == null
                || temStoreEntity.getTemId().longValue() != temStoreEntity1.getTemId().longValue())) {
            throw new RRException("模板名称不能重复");
        }
        if (temStoreEntity.getTemId() == null) {
            temStoreEntity.setCreator(SecurityUtils.getUserId())
                    .setTemId(cachedUidGenerator.getUID())
                    .setCreateTime(LocalDateTime.now())
                    .setStatus(1)
                    .setDeleted(Boolean.FALSE);
        }
        saveOrUpdate(temStoreEntity);
        return true;
    }

}